import kkBaseData from 'kkBaseData'
import kkCache from 'kkCacheData'
import kkApi from 'kkApi'

/**
 * 将数字（秒数）转化成 mm:ss 格式
 * @param {Number} secondNum 
 */
export const formatSeconds = (secondNum) => {
    let secondString = ""
    let theTime = parseInt(secondNum) // 秒 
    let time_m = 0 // 分 
    let theTimeString = ''
    let time_mString = ''
    if (theTime > 60) {
        time_m = theTime / 60
        theTime = theTime % 60
    }
    theTimeString = theTime < 10 ? '0' + theTime : '' + theTime
    time_mString = time_m < 10 ? "0" + time_m : '' + time_m

    secondString = time_mString + ":" + theTimeString
    return secondString
}

// 获取当前是第几周
const getWeek = () => {
    const d1 = new Date()
    const d2 = new Date()
    d2.setMonth(0)
    d2.setDate(1)
    const rq = Number(d1) - Number(d2)
    const s1 = Math.ceil(rq / (24 * 60 * 60 * 1000))
    const s2 = Math.ceil(s1 / 7)

    return s2
}

/**
 * 获取当前年月日 YYYY-MM-DD 格式
 */
export const getNowDate = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = now.getMonth() + 1
    const date = now.getDate()

    const str = year + "-" + month + "-" + date

    return str
}

const timesTampToStrDate = (timeTamp) => {
    const now = new Date(timeTamp)
    const year = now.getFullYear()
    const month = now.getMonth() + 1
    const date = now.getDate()
    const str = year + "-" + month + "-" + date

    return str
}

const timeWrapper = {

    initTimer() { // 初始化时间模块
        this.countOfflineSecond() // 先计算出离线时间，存到缓存中
        this.updateOnlineTime() // 更新时间戳
        setInterval(this.updateOnlineTime, 1000 * 60) // 每分钟更新一次上次在线的时间戳
    },

    // 计算离线时间(秒)
    countOfflineSecond() {
        // 目前时间戳减上次的时间戳
        if (kkBaseData.lastOnlineTime !== 0) {
            let offlineTime = Date.now() - kkBaseData.lastOnlineTime
            let offlineSeconds = Math.floor(offlineTime / 1000)
            // cc.log('离线', offlineSeconds, '秒')
            kkCache.offlineSeconds = offlineSeconds
        }
    },

    // 更新上一次在线的时间戳，和计算统计逻辑
    updateOnlineTime() {
        kkBaseData.lastOnlineTime = Date.now()
        kkBaseData.statisticalData.totalOnlineMinute += 1 // 累计总在线分钟加一
        // cc.log('保存时间')
        kkApi.saveData()
    },

    getNowDate,
    formatSeconds
}

export default timeWrapper